package singlelink;

/**
 * Created by wuwf on 2017/3/25.
 * 单链表
 */
public class LinkedList {
    private int size;
    /*
     * 头节点
     */
    private Node head;

    public LinkedList() {
        size = 0;
    }

    public int size() {
        return size;
    }

    public void print() {
        if (size == 0) {
            System.out.println("空列表");
            return;
        }
        Node node = head;
        while (node != null) {
            System.out.println(node.getData());
            node = node.getNext();
        }
    }

    /**
     * 在末尾追加一个节点
     *
     * @param node
     */
    public void add(Node node) {
        if (node == null) {
            return;
        }
        //如果链表为空,那新增的这个node就作为head
        if (size == 0) {
            head = node;
        } else { //添加到末尾
            Node last = head;
            while (last.getNext() != null) {
                last = last.getNext();
            }
            last.setNext(node);
        }
        size++;
    }

    /**
     * 在某个位置插入一个节点
     *
     * @param index
     * @param node
     */
    public void insert(int index, Node node) {
        if (index < 0 || index > size) {
            throw new RuntimeException("越界");
        }
        if (node == null) {
            return;
        }
        //插头部
        if (index == 0) {
            node.setNext(head);
            head = node;
        } else {
            Node tempNode = head;
            for (int i = 0; i < index - 1; i++) {
                //取到要被插入的节点的父节点
                tempNode = tempNode.getNext();
            }
            node.setNext(tempNode.getNext());
            tempNode.setNext(node);
        }
        size++;
    }

}
